package com.fpd.tools;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import lombok.extern.slf4j.Slf4j;

/**
 * @desc 文件工具类
 * @author wujiangbo
 * @date 2019年11月7日 上午11:54:53
 */
@Component
@Slf4j
public class FileUtil {

	@Value("${oss.endpoint}")
	private String ossEndpoint;

	@Value("${oss.host}")
	private String ossUrlHost; // 上传文件路径

	@Value("${oss.accessKeyId}")
	private String ossAccessKeyId;

	@Value("${oss.accessKeySecret}")
	private String ossAccessKeySecret;

	@Value("${oss.bucket}")
	private String ossBucket;

	@Autowired(required = false)
	private HttpServletRequest requestAutowired;

	@Value("${websiteUrl}")
	private String websiteUrl;

	public TemplateExportParams getTemplateExportParams1(String modelFileName) {
//		String path1 = this.getClass().getResource(modelUrl).getPath();
		String path1 = requestAutowired.getSession().getServletContext().getRealPath("/WEB-INF") + File.separator + "classes" + File.separator + "model" + File.separator;
		path1 = path1 + modelFileName;
//		path1 = path1.replace(":", ":/");
//		if (path1.contains(":")) {
//			path1 = path1.substring(1, path1.length());
//		}
		return new TemplateExportParams(path1);
	}

	public TemplateExportParams getTemplateExportParams(String modelFileName) {
		Resource resource = new ClassPathResource("model" + File.separator + modelFileName);
		/**
		 * 有些系统提示找不到资源，可以把上面的代码换成下面这句： ClassPathResource resource = new
		 * ClassPathResource("model" + File.separator +modelFileName);
		 */
		File sourceFile;
		TemplateExportParams tep = new TemplateExportParams();
		try {
			sourceFile = resource.getFile();
			tep.setTemplateUrl(sourceFile.getAbsolutePath());
		} catch (IOException e) {
			log.error("FileUtil ---- getTemplateExportParams 异常：{}", e);
		}
		return tep;
	}

	public TemplateExportParams getTemplateExportParamsSheets(String modelFileName) {
		Resource resource = new ClassPathResource("model" + File.separator + modelFileName);
		/**
		 * 有些系统提示找不到资源，可以把上面的代码换成下面这句： ClassPathResource resource = new
		 * ClassPathResource("model" + File.separator +modelFileName);
		 */
		File sourceFile;
		TemplateExportParams tep = null;
		try {
			sourceFile = resource.getFile();
			tep = new TemplateExportParams(sourceFile.getAbsolutePath(), true);
		} catch (IOException e) {
			log.error("FileUtil ---- getTemplateExportParams 异常：{}", e);
		}
		return tep;
	}

	/**
	 * 上传文件至本地
	 *
	 * @param file
	 * @param filePath
	 * @param fileName
	 * @throws Exception
	 */
	public static void uploadFile(byte[] file, String filePath, String fileName) {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(filePath + fileName);
			out.write(file);
			out.flush();
		} catch (FileNotFoundException e) {
			log.error("uploadFile -- FileNotFoundException", e);
		} catch (IOException e) {
			log.error("uploadFile -- IOException", e);
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					log.error("uploadFile -- out.close()", e);
				}
			}
		}
	}

	// 上传文件
	/**
	 * @desc
	 * @author wujiangbo
	 * @date 2019年12月13日 下午2:22:31
	 * @param file           文件
	 * @param uploadFilePath 保存路径
	 * @param file_name      文件名
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	public String uploadFileUtil(MultipartFile file, String uploadFilePath, String file_name) throws IllegalStateException, IOException {
		String path_prefix1 = requestAutowired.getSession().getServletContext().getRealPath("/WEB-INF") + File.separator + "classes" + File.separator;
		String path_prefix2 = "static" + File.separator;
		String fileOriginalName = file.getOriginalFilename();
		String fileName_temp = fileOriginalName.substring(0, fileOriginalName.lastIndexOf("."));// 文件名，不带文件类型
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = Tool.isBlank(file_name) ? (fileName_temp + Tool.getCurrentTimeString()) : file_name;
		String returnString = path_prefix2 + uploadFilePath + File.separator + Tool.getCurrentYearMonth();
		uploadFilePath = path_prefix1 + returnString;
		File fileTemp = new File(uploadFilePath);
		if (!fileTemp.isDirectory()) {////如果fileTemp表示的不是一个目录则返回true
			fileTemp.mkdirs();//创建目录
		}
		String fileFullName = uploadFilePath + File.separator + fileName + suffix;
		File targetFile = new File(fileFullName);
		file.transferTo(targetFile.getAbsoluteFile());// 保存文件
		return path_prefix1+returnString + File.separator + fileName + suffix;
	}

//	public static void main(String[] args) throws FileNotFoundException {
//		String url = "http://fpd-yima.oss-cn-shanghai.aliyuncs.com/hecheng/UploadRoot/lawerTemplate/2019121617475444630799765.docx";
//		uploadOssFile(url, "d://123//456");
//	}

	/**
	 * @desc 将OSS上的文件下载到指定文件夹下
	 * @author wujiangbo
	 * @date 2019年12月16日 下午6:39:35
	 * @param url            oss文件全路径
	 * @param targetFilePath 指定文件夹
	 * @return
	 */
	public String downloadOssFile(String url, String targetFilePath) {
		String str = "";
		try {
			File file = new File(targetFilePath);
			if (!file.exists()) {//如果bai存在的话返duzhi“true”，否则就是dao返zhuan“false”
				file.mkdirs();
			}
			File urlFile = new File(url);
			String fileName = urlFile.getName();
			str = targetFilePath + File.separator + fileName;
			File targetFile = new File(str);
			FileOutputStream outputStream = new FileOutputStream(targetFile);
			getBarCodeImgByUrl(url, outputStream);
		} catch (FileNotFoundException e) {
			log.error("uploadOssFile -- FileNotFoundException()", e);
		} catch (IOException e) {
			log.error("uploadOssFile -- IOException()", e);
		}
		return str;
	}

	// 公共方法根据url生成二维码图片后写入输出流里
	public void getBarCodeImgByUrl(String url, OutputStream os) throws IOException {
		URL urlConet = new URL(url);
		HttpURLConnection con = (HttpURLConnection) urlConet.openConnection();
		con.setRequestMethod("GET");
		con.setConnectTimeout(4 * 1000);
		InputStream inStream = con.getInputStream(); // 通过输入流获取图片数据
		byte[] buffer = new byte[2048];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			os.write(buffer, 0, len);
		}
		inStream.close();
	}

	public File multipartFileToFile(MultipartFile file) {
		try {
			String fileName = file.getOriginalFilename();
			// 获取文件后缀
			String prefix = fileName.substring(fileName.lastIndexOf("."));
			// 用uuid作为文件名，防止生成的临时文件重复
			final File pdfFile = File.createTempFile("上传Excel文档" + DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_YYYY_MM_DD), prefix);
			// MultipartFile to File
			file.transferTo(pdfFile);
			return pdfFile;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * @desc 上传文件到OSS上
	 * @author wujiangbo
	 * @date 2019年12月16日 下午4:09:33
	 * @param file              文件
	 * @param uploadOssFilePath 储存路径
	 * @return
	 */
	public String uploadOssFileUtil(File file, String uploadOssFilePath) {
		String fileOriginalName = file.getName();
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = Tool.getFileName();
		String fileFullName = uploadOssFilePath + fileName + suffix;
		boolean uploadResult = uploadMultipartFileOss(fileFullName, file);
		if (!uploadResult) {
			return "-1";
		}
		return ossUrlHost + fileFullName;
	}

	public String uploadOssFileUtil(MultipartFile file, String uploadOssFilePath) {
		String fileOriginalName = file.getOriginalFilename();
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = Tool.getFileName();
		String fileFullName = uploadOssFilePath + fileName + suffix;
		boolean uploadResult = uploadMultipartFileOss(fileFullName, file);
		if (!uploadResult) {
			return "uploadFailed";
		}
		return ossUrlHost + fileFullName;
	}

	/**
	 * 上传文件至oss
	 *
	 * @param uploadOssFilePath 文件路径
	 * @param file              上传的文件
	 */
	public boolean uploadMultipartFileOss(String uploadOssFilePath, File file) {
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		String endpoint = ossEndpoint;
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录
		// https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = ossAccessKeyId;
		String accessKeySecret = ossAccessKeySecret;

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		boolean uploadResult = false;
		// 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
		try {
			ossClient.putObject(ossBucket, uploadOssFilePath, file);
			uploadResult = true;
		} catch (OSSException e) {
			uploadResult = false;
			log.error("uploadFileOss -- OSSException", e);
		} catch (ClientException e) {
			uploadResult = false;
			log.error("uploadFileOss -- ClientException", e);
		} finally {
			// 关闭OSSClient。
			ossClient.shutdown();
		}
		return uploadResult;
	}

	public boolean uploadMultipartFileOss(String uploadOssFilePath, MultipartFile file) {
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		String endpoint = ossEndpoint;
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录
		// https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = ossAccessKeyId;
		String accessKeySecret = ossAccessKeySecret;

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		boolean uploadResult = false;
		// 上传文件。<yourLocalFile>由本地文件路径加文件名包括后缀组成，例如/users/local/myfile.txt。
		try {
			ossClient.putObject(ossBucket, uploadOssFilePath, file.getInputStream());
			uploadResult = true;
		} catch (OSSException e) {
			uploadResult = false;
			log.error("uploadFileOss -- OSSException", e);
		} catch (ClientException e) {
			uploadResult = false;
			log.error("uploadFileOss -- ClientException", e);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭OSSClient。
			ossClient.shutdown();
		}
		return uploadResult;
	}

	// 删除Oss上的文件
	public boolean deleteOssFile(String filePath) {
		// Endpoint以杭州为例，其它Region请按实际情况填写。
		String endpoint = ossEndpoint;
		// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录
		// https://ram.console.aliyun.com 创建RAM账号。
		String accessKeyId = ossAccessKeyId;
		String accessKeySecret = ossAccessKeySecret;

		// 创建OSSClient实例。
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		boolean uploadResult = true;
		try {
			ossClient.deleteObject(ossBucket, filePath);
		} catch (Exception e) {
			uploadResult = false;
			log.error("deleteOssFile---删除Oss文件失败：{}", e);
		} finally {
			// 关闭OSSClient。
			ossClient.shutdown();
		}
		return uploadResult;
	}

	/**
	 * 删除
	 *
	 * @param files
	 */
	public void deleteFile(File... files) {
		for (File file : files) {
			if (file.exists()) {
				file.delete();
			}
		}
	}

	public String uploadLinuxFileUtil(MultipartFile file, String uploadLinuxFilePath){
		String yearMonth = Tool.getCurrentYearMonth();
		String dirPath = uploadLinuxFilePath+yearMonth;
		File dir = new File(uploadLinuxFilePath+yearMonth);
		if(!dir.exists()){
			dir.mkdirs();
		}
		String fileOriginalName = file.getOriginalFilename();
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = Tool.getFileName()+suffix;
		File targetFile = new File(dir,fileName);
		try {
			file.transferTo(targetFile.getAbsoluteFile());
		}catch (IOException e){
			e.printStackTrace();
		}
		return websiteUrl + dirPath +"/"+fileName;
	}

	public String uploadLinuxFileUtil(File file, String uploadLinuxFilePath){
		String yearMonth = Tool.getCurrentYearMonth();
		String dirPath = uploadLinuxFilePath+yearMonth;
		File dir = new File(uploadLinuxFilePath+yearMonth);
		if(!dir.exists()){
			dir.mkdirs();
		}
		String fileOriginalName = file.getName();
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = Tool.getFileName()+suffix;
		File targetFile = new File(dir,fileName);
		try {
			Files.copy(file.toPath(), targetFile.toPath());
			return websiteUrl + dirPath + "/" + fileName;
		}catch (IOException e){
			e.printStackTrace();
		}
		return "";
	}
	
	public String uploadLinuxFileUtil2(File file, String uploadLinuxFilePath, String newName){
		String yearMonth = Tool.getCurrentYearMonth();
		String dirPath = uploadLinuxFilePath+yearMonth;
		File dir = new File(uploadLinuxFilePath+yearMonth);
		if(!dir.exists()){
			dir.mkdirs();
		}
		String fileOriginalName = file.getName();
		String suffix = fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		String fileName = newName + suffix;
		File targetFile = new File(dir,fileName);
		try {
			Files.copy(file.toPath(), targetFile.toPath());
			return websiteUrl + dirPath + "/" + fileName;
		}catch (IOException e){
			e.printStackTrace();
		}
		return "";
	}
	
	public static void main(String[] args) {
		String fileOriginalName = "/qwe/rr/66/dfgwqeqweqwe.xcel";
		File file = new File(fileOriginalName,"11");
		System.out.println(file.getName());
		System.out.println(fileOriginalName.substring(fileOriginalName.lastIndexOf(".")));
	}

}
